package com.dou.sample.opengl_project;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

/**
 * Created by Dou on 2018/1/15.
 */

public class Mesh {
    FloatBuffer vertexBuffer = null;
    ShortBuffer indicesBuffer = null;
    FloatBuffer colorBuffer = null;

    float[] rgba = {1,1,1,1};

    float x,y,z = 0;
    float rx,ry,rz;

    int numberOfIndices = -1;

    public void draw(GL10 gl){
        gl.glFrontFace(GL10.GL_CCW);
        gl.glEnable(GL10.GL_CULL_FACE);
        gl.glCullFace(GL10.GL_BACK);
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glVertexPointer(3, GL10.GL_FLOAT,0,vertexBuffer);
        gl.glColor4f(rgba[0],rgba[1],rgba[2],rgba[3]);
        if (colorBuffer != null){
            gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
            gl.glColorPointer(4,GL10.GL_FLOAT,0,colorBuffer);
        }
        gl.glTranslatef(x, y, z);
        gl.glRotatef(rx, 1, 0, 0);
        gl.glRotatef(rx, 0, 1, 0);
        gl.glRotatef(rx, 0, 0, 1);

        gl.glDrawElements(GL10.GL_TRIANGLES,numberOfIndices, GL10.GL_UNSIGNED_SHORT,indicesBuffer);
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisable(GL10.GL_CULL_FACE);
    }

    protected void setVertex(float[] vertex){
        ByteBuffer vertexByteBuffer = ByteBuffer.allocateDirect(vertex.length * 4);
        vertexByteBuffer.order(ByteOrder.nativeOrder());
        vertexBuffer = vertexByteBuffer.asFloatBuffer();
        vertexBuffer.put(vertex);
        vertexBuffer.position(0);
    }

    protected void setIndices(short[] indices){
        ByteBuffer indiceByteBuffer = ByteBuffer.allocateDirect(indices.length * 2);
        indiceByteBuffer.order(ByteOrder.nativeOrder());
        indicesBuffer = indiceByteBuffer.asShortBuffer();
        indicesBuffer.put(indices);
        indicesBuffer.position(0);
    }

    protected void setColor(float red, float green, float blue, float alpha){
        rgba[0] = red;
        rgba[1] = green;
        rgba[2] = blue;
        rgba[3] = alpha;
    }

    protected void setColors(float[] colors){
        ByteBuffer colorByteBuffer = ByteBuffer.allocateDirect(colors.length * 4);
        colorByteBuffer.order(ByteOrder.nativeOrder());
        colorBuffer = colorByteBuffer.asFloatBuffer();
        colorBuffer.put(colors);
        colorBuffer.position(0);
    }
}
